package tako.wisers.com.android.upload;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;



public class RequestDecompose implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8145669855025568079L;

	/**
	 * @param args
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws FileNotFoundException,
			IOException {
		// getFileEntity();
	}
	
	private int contentIndex;

	@SuppressWarnings("unchecked")
	public List<Object> getFileEntity(HttpServletRequest req,
			String charset, Long version) throws Exception {
		String header = req.getHeader("header");
		String end = req.getHeader("end");
		byte[] headerbyte = null;
		byte[] endbyte = null;
		if(header != null && end != null){
			headerbyte = reqHeader2Bytes(header);
			endbyte = reqHeader2Bytes(end);
		}else{
			return null;
		}
		
		byte[] bytes = IOUtils.toByteArray(req.getInputStream());
		
		int headerIndex = getBytesHeader(bytes,headerbyte);
		int endIndex = getBytesEnd(bytes,endbyte);
		ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes,headerIndex,endIndex - headerIndex + 1));
		List<Object> obj = (List<Object>)ois.readObject();
//		System.out.println(obj);
		return obj;
	}
	
	private int getBytesHeader(byte[] content,byte[] header){
		contentIndex = 0;
		if(markObjectByte(content,header,0,0)){
			return contentIndex - header.length + 1;
		}
		return -1;
	}
	
	private int getBytesEnd(byte[] content,byte[] end){
		contentIndex = content.length - 200;
		if(content.length < 200){
			contentIndex = 0;
		}
		if(markObjectByte(content,end,contentIndex,0)){
			return contentIndex;
		}
		return -1;
	}
	
	private boolean markObjectByte(byte[] content,byte[] mark,int contentIndex,int markIndex){
		if(contentIndex >= content.length){
			return false;
		}
		if(content[contentIndex] == mark[markIndex]){
			if(markIndex == mark.length - 1){
				this.contentIndex = contentIndex;
				return true;
			}
			return markObjectByte(content,mark,contentIndex + 1,markIndex + 1);
		}else{
			return markObjectByte(content,mark,contentIndex - markIndex + 1,0);
		}
	}

	private byte[] reqHeader2Bytes(String str){
		String[] bs = str.split(",");
		if(bs.length == 0){
			return null;
		}
		byte[] bytes = new byte[bs.length];
		for(int i=0;i<bs.length;i++){
			bytes[i] = new Byte(bs[i]);
		}
		return bytes;
	}
}
